package com.yanxu;

import java.io.IOException;
import java.net.*;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025-06-05-2025
 * @Description: DatagramSocket api 相关学习
 */
public class DatagramSocket_Api {
    public static void main(String[] args) throws IOException {
        // 使用无参数构造方法创建 DatagramSocket
        //DatagramSocket datagramSocket1 = new DatagramSocket();

        // 指定监听端口，创建 DatagramSocket
        //DatagramSocket datagramSocket = new DatagramSocket(7777);

        // 指定监听端口，以及 ip地址，创建 DatagramSocket
        //InetAddress byName = Inet4Address.getByName("192.168.1.30");
        InetAddress inetAddress = InetAddress.getByName("192.168.1.30");
        DatagramSocket datagramSocket = new DatagramSocket(6666, inetAddress);
        datagramSocket.setSoTimeout(3000);

        // 发送数据
        String msg = "helloworld";
        byte[] msgBytes = msg.getBytes();
        DatagramPacket sendDatagramPacket = new DatagramPacket(
                msgBytes,
                0,
                msgBytes.length,
                new InetSocketAddress("192.168.1.33", 9999));

        datagramSocket.send(sendDatagramPacket);

        // 接收数据
        DatagramPacket receiveDatagramPacket = new DatagramPacket(new byte[1024], 1024);
        datagramSocket.receive(receiveDatagramPacket);

        // 释放资源
        datagramSocket.close();
    }
}